//
// Created by Zain on 2016/9/9.
//

#include "FileInputStream.h"

using namespace ZainTL;
using namespace std;

FileInputStream::FileInputStream(const char *path) : InputStream(path) {
    mIStream = new ifstream(path, fstream::in | fstream::binary);
}

std::streamsize FileInputStream::read(char *buffer, std::streamsize bufferSize) {
    ifstream *fileInputStream = (ifstream *) mIStream;
    fileInputStream->read(buffer, bufferSize);
    return fileInputStream->gcount();
}

FileInputStream::~FileInputStream() {
    if (mIStream) {
        ((ifstream *) mIStream)->close();
        delete (mIStream);
        mIStream = NULL;
    }
}

std::streamsize FileInputStream::available() {
    streampos pos = mIStream->tellg();

    mIStream->seekg(0, fstream::end);
    std::streamsize size = mIStream->tellg();

    mIStream->seekg(pos);

    return size;
}

bool FileInputStream::eof() {
    streampos pos = mIStream->tellg();

    mIStream->seekg(0, fstream::end);
    std::streamsize size = mIStream->tellg();

    mIStream->seekg(pos);
    return pos >= size;
}

uint16_t FileInputStream::getShort() {
    char buffer[2];
    read(buffer, 2);
    return byteArrayToUint(buffer, 2);
}

uint64_t FileInputStream::getLong() {
    char buffer[8];
    read(buffer, 8);
    return byteArrayToUint(buffer, 8);
}

char FileInputStream::getChar() {
    char buffer[1];
    read(buffer, 1);
    return buffer[0];
}
